package com.xhsj.user.hr.system.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.entity.MenuTree;
import com.xhsj.user.hr.system.entity.TbGlobalMenu;
import com.xhsj.user.hr.system.entity.TbGlobalRole;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.xhsj.user.hr.system.query.GetListByParentIdQuery;
import com.xhsj.user.utils.UserUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.*;
import java.util.stream.Collectors;

import com.xhsj.user.utils.Message;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.web.bind.annotation.RestController;


import com.xhsj.user.hr.system.service.TbGlobalMenuService;

import javax.servlet.http.HttpServletRequest;


/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author suxl
 * @since Aug 27, 2020 10:36:16 AM
 */
@Slf4j
@Api(tags = "菜单权限表")
@RestController
@RequestMapping("/menu/tbGlobalMenu")
public class TbGlobalMenuController {

	@Autowired
    public TbGlobalMenuService service;

	@Autowired
	private TbGlobalRoleMapper tbGlobalRoleMapper;


	/**
	 * 保存/修改
	 * @author suxl
	 * @date Aug 27, 2020 10:36:16 AM
	 */
	@ApiOperation(value = "菜单权限表,保存/修改", notes = "菜单权限表,保存和修改方法")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
 	@PreAuthorize("hasAuthority('tb:sys:menu:edit')")
	public Message save(@RequestBody TbGlobalMenu data){
		System.out.println(JSON.toJSONString(data));

		JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data), Feature.OrderedField);

		System.out.println(JSON.toJSONString(jsonObject));
		try {
    		service.save(data);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
        	return Message.error(1,"失败");
		}

	}

	/**
	 * 通过id删除数据
	 * @author suxl
	 * @date Aug 27, 2020 10:36:16 AM
	 */
	@ApiOperation(value = "菜单权限表删除", notes = "通过id删除菜单权限表信息。")
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('tb:sys:menu:delete')")
	public Message delete(@RequestParam(value="id") Long id) {
		try {
			service.delById(id);
        	return Message.success("成功");
		} catch (Exception e) {
			log.error("删除失败:{}",e);
            return Message.error(1,"失败");
		}

	}

	/**
	 * 批量删除
	 * @author suxl
	 * @date Aug 27, 2020 10:36:16 AM
	 */
	@ApiOperation(value = "批量删除", notes = "批量删除。")
	@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('tb:sys:menu:delete')")
	public Message batchDelete(@RequestBody List<String> list) {
		try {
			service.removeByIds(list);
    		return Message.success("成功");
		} catch (Exception e) {
    		log.error("删除失败:{}",e);
    		return Message.error(1,"失败");
		}
    }

    /**
    * 分页查询数据
    * @author suxl
    * @date Aug 27, 2020 10:36:16 AM
    */
	@ApiOperation(value = "分页查询菜单权限表list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
	@RequestMapping(value="/findList",method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('tb:sys:menu:view')")
	public Message findList(@RequestBody Map<String,Object> data) {
        try {
        	IPage<TbGlobalMenu> selectPage = service.selectPage(data);
    		return Message.success("成功",selectPage.getRecords(),selectPage.getTotal(),selectPage.getPages());
        } catch (Exception e) {
			log.error("查询异常:{}",e);
    		return Message.error(1,"失败");
        }
	}

	/**
	 * 查询当前用户菜单
	 * @author 苏小林
	 * @date 2020/9/1 17:43
	 * @param: request
	 * @return: com.xhsj.user.utils.Message
	 */
	@ApiOperation(value = "查询当前用户菜单", notes = "查询当前用户菜单。")
	@RequestMapping(value="/findCurrentMenus",method = RequestMethod.GET)
	public Message findCurrentMenus(HttpServletRequest request){
		try {
			//获取当前登录用户
			LoginUser loginAppUser = UserUtils.getLoginAppUser();
			Set<TbGlobalRole> sysRoles = tbGlobalRoleMapper.getRoleByUserId(loginAppUser.getUserId());
			boolean flag = false;
			// 判断当前用户角色是不是超级管理员
			for (TbGlobalRole sysRole : sysRoles) {
				if (sysRole.getRoleId() == 1) {
					flag = true;
					break;
				}
			}
			// 超级管理员
			if (flag) {
				// 查询菜单列表
				QueryWrapper<TbGlobalMenu> menuWrapper = new QueryWrapper<>();
				menuWrapper.eq("menu_type",0);// 菜单
				menuWrapper.ne("id",1);// id 不为1
//				menuWrapper.eq("visible",0);// 0 显示
				List<TbGlobalMenu> menuList = service.list(menuWrapper);
				List<TbGlobalMenu> father = menuList.stream().filter(sysMenu -> sysMenu.getParentId() == 1).collect(Collectors.toList());
				father.sort((a, b) -> a.getOrderNum() - b.getOrderNum());
				service.setSubChild(father,menuList);
				return Message.success("成功",father);
			}

			//查询菜单集合
			if (!CollectionUtils.isEmpty(sysRoles)){
				Set<Long> roleIds = sysRoles.parallelStream().map(TbGlobalRole::getRoleId).collect(Collectors.toSet());
				Set<TbGlobalMenu> allMenuList=service.getMenuByRoleIds(roleIds);
				List<TbGlobalMenu> menuList = Lists.newArrayList(allMenuList);
				if (!CollectionUtils.isEmpty(menuList)){
					List<TbGlobalMenu> father = menuList.stream().filter(sysMenu -> sysMenu.getParentId() == 1).collect(Collectors.toList());
					father.sort((a, b) -> a.getOrderNum() - b.getOrderNum());
					service.setSubChild(father,menuList);
					return Message.success("成功",father);
				}
			}

			return Message.success("成功", Lists.newArrayList());
		} catch (Exception e) {
			log.error("异常:{}",e);
			return Message.error(1,"失败");
		}
	}

	/**
	 * 查询权限
	 * @author 苏小林
	 * @date 2020/9/9 9:40
	 * @return: com.xhsj.user.utils.Message
	 */
	@ApiOperation(value = "查询权限", notes = "查询权限")
	@RequestMapping(value = "/findPermissions", method = RequestMethod.GET)
	public Message findPermissions(){
		try {

			//获取当前登录用户
			LoginUser loginAppUser = UserUtils.getLoginAppUser();
			Set<TbGlobalRole> sysRoles = tbGlobalRoleMapper.getRoleByUserId(loginAppUser.getUserId());
			boolean flag = false;
			// 判断当前用户角色是不是超级管理员
			for (TbGlobalRole sysRole : sysRoles) {
				if (sysRole.getRoleId() == 1) {
					flag = true;
					break;
				}
			}

			if (flag) { // 超级管理员
				// 查询权限列表
				QueryWrapper<TbGlobalMenu> wrapper = new QueryWrapper<>();
				wrapper.eq("menu_type",1);// 权限
				List<TbGlobalMenu> list = service.list(wrapper);
				Set<String> permissions = list.parallelStream().map(TbGlobalMenu::getPerms)
						.collect(Collectors.toSet());
				return Message.success("查询成功",permissions);
			} else {
				//查询权限集合
				Set<Long> roleIds = sysRoles.parallelStream().map(TbGlobalRole::getRoleId).collect(Collectors.toSet());
				if (!CollectionUtils.isEmpty(sysRoles)) {
					Set<TbGlobalMenu> sysPermissions=service.getPermissionByRoleIds(roleIds);
					if (!CollectionUtils.isEmpty(sysPermissions)) {
						Set<String> permissions = sysPermissions.parallelStream().map(TbGlobalMenu::getPerms)
								.collect(Collectors.toSet());
						return Message.success("查询成功",permissions);
					}
				}
			}
			return Message.success("查询成功",null);
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("查询失败");
		}
	}

	/**
	 * 查询所有菜单权限
	 * @author 苏小林
	 * @date 2020/9/1 17:44
	 */
	@ApiOperation(value = "查询所有菜单权限", notes = "查询所有菜单权限。")
	@RequestMapping(value="/getAllMenusAndPerm",method = RequestMethod.GET)
	public Message getAllMenusAndPerm() {
		try {
			QueryWrapper<TbGlobalMenu> menuWrapper = new QueryWrapper<>();
			menuWrapper.ne("id","1");// id 不为1
			List<TbGlobalMenu> list = service.list(menuWrapper);
			List<TbGlobalMenu> father = list.stream().filter(tbGlobalMenu -> tbGlobalMenu.getParentId() == 1).collect(Collectors.toList());
			service.setSubChild(father,list);
			return Message.success("成功",father);
		} catch (Exception e) {
			log.error("异常:{}",e);
			return Message.error(1,"失败");
		}
	}

	@ApiOperation(value = "查询菜单树", notes = "查询菜单树。")
	@RequestMapping(value="/findMenuTree",method = RequestMethod.GET)
	public Message findMenuTree() {

		try {
			List<MenuTree> list = service.findMenuTree();
			List<MenuTree> father = list.stream().filter(menuTree -> menuTree.getParentId() == 1).collect(Collectors.toList());
			service.setSubChild(father,list);
			System.err.println(father);
			return Message.success("成功",father);
		} catch (Exception e) {
			log.error("异常:{}",e);
			return Message.error(1,"失败");
		}

	}

	@ApiOperation(value = "通过父id查询列表", notes = "通过父id查询列表。")
	@RequestMapping(value="/getListByParentId",method = RequestMethod.POST)
	public Message getListByParentId(@RequestBody GetListByParentIdQuery getListByParentIdQuery) {

		try {
			IPage<TbGlobalMenu> iPage = service.getListByParentId(getListByParentIdQuery);
			return Message.success("成功",iPage.getRecords(),iPage.getTotal(),iPage.getPages());
		} catch (Exception e) {
			log.error("异常:{}",e);
			return Message.error(1,"失败");
		}

	}

    /**
    * 查询所有数据
    * @author suxl
    * @date Aug 27, 2020 10:36:16 AM
    */
	@ApiOperation(value = "查询菜单权限表所有数据list", notes = "查询菜单权限表所有数据list。")
	@RequestMapping(value="/findAll",method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('tb:sys:menu:view')")
	public Message findAll(){
        return Message.success("成功",service.selectAll());
	}

    /**
    * 通过id获取实体类
    * @author suxl
    * @date Aug 27, 2020 10:36:16 AM
    */
	@ApiOperation(value = "通过id获取菜单权限表实体类", notes = "通过id获取菜单权限表实体类。")
	@RequestMapping(value="/getById",method = RequestMethod.GET)
	public Message getById(@RequestParam(value="id") String id) {
    	return Message.success("成功",service.getById(id));
	}

    /**
    * 通过id查询详细信息
    * @author suxl
    * @date Aug 27, 2020 10:36:16 AM
    */
	@ApiOperation(value = "通过id获取实体类详细信息", notes = "通过id获取实体类详细信息。")
	@RequestMapping(value="/detail",method = RequestMethod.GET)
	public Message detail(@RequestParam(value="id") String id) {
    	return Message.success("成功",service.getById(id));
	}

}

